package com.woniuxy.educationplatform.controller;

import com.woniuxy.educationplatform.service.IGoodsService;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/files")
 public class GoodsFileUpLoadController {
    @Resource
    private IGoodsService goodsServiceImpl;
    /**
     * 下载
     * @param fileName 文件的名称
     * @param userAgent 浏览器的种类
     * @return 设置响应的实体对象 由于我们现在是返回的图片，所以我们以字节数组的方式来返回
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String fileName, @RequestHeader("User-Agent") String userAgent){
        String filePath = "D://img" + File.separator + fileName;
        System.out.println(filePath);
        File file = new File(filePath);
        if(file.exists()){
            try{
                //构建一个响应状态码 200
                ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
                //设置文件的长度
                builder.contentLength(file.length());
                //告诉前端，后端现在给你的数据类型是：二进制流
                builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
                fileName = URLEncoder.encode(fileName, "UTF-8");
                //判断浏览器是否是IE浏览器
                if(userAgent.indexOf("MSIE") > 0) {
                    builder.header("Content-Disposition", "attachment; filename=" + fileName);
                }else {
                    builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + fileName);
                }

                //通过FileUtils工具类，读取文件到 响应体中
                return builder.body(FileUtils.readFileToByteArray(file));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    @PostMapping("/upload")
    public String filesUpload(@RequestParam("file")MultipartFile file){

        //输出一下文件的名称
        String originalFileName =  file.getOriginalFilename();

        //如果有文件服务器，则将该文件上传至FTP文件服务器上去
        //如果没有文件服务器，就将该文件持久化到本地磁盘中去
//        String path = "D:/Program Files/IdeaProjects/TMStransport2/src/main/resources/static/img";
        String path = "D:/idea-workspace/ep/src/main/resources/static/goodsImage";
        String carPhoto="../static/goodsImage/"+originalFileName;
        System.out.println(carPhoto);
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }
        //向文件夹中写入该文件
        String filePath = path + File.separator + originalFileName;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return carPhoto;
    }
}

